import { createRouter, createWebHistory } from 'vue-router'
import { routes } from './routes'
import { useUserStore } from '@/store/user'

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 白名单路由
  const whiteList = ['/login', '/register']
  
  if (whiteList.includes(to.path)) {
    // 如果是白名单页面，已登录则跳转首页，未登录则直接访问
    if (token && to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    // 非白名单页面，未登录则跳转登录页
    if (!token) {
      next('/login')
    } else {
      next()
    }
  }
})

export default router 